"""
ReAct 流式聊天API - 支持思考过程的实时流式输出
"""

import asyncio
import json
import logging
import time
from typing import Dict, List, Any, Optional

from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from sqlalchemy import text

from app.configs.database import get_db
from app.services.react_streaming_service import ReactStreamingService
from app.services.hybrid_conversation_service import HybridConversationService
from app.api.endpoints.auth import get_current_user
from app.models import User

logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter()

# 请求模型
class ReactStreamRequest(BaseModel):
    message: str = Field(..., description="用户消息")
    conversation_id: Optional[str] = Field(None, description="对话ID")
    user_id: Optional[str] = Field(None, description="用户ID")
    include_history: bool = Field(True, description="是否包含对话历史")
    max_history: int = Field(10, description="最大历史消息数量")

# 响应模型
class ReactStreamResponse(BaseModel):
    message: str = Field(..., description="响应消息")
    stream_url: str = Field(..., description="流式响应URL")


@router.post("/react-stream")
async def react_stream_chat(
    request: ReactStreamRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # 立即打印，确认函数被调用
    print("🚨🚨🚨 REACT-STREAM FUNCTION CALLED! 🚨🚨🚨")
    print(f"🚨 Request message: {request.message}")
    print(f"🚨 Current user: {current_user.email if current_user else 'None'}")
    print("🚨🚨🚨 END CONFIRMATION 🚨🚨🚨")
    """
    ReAct 流式聊天接口 - 实时返回思考过程和最终答案
    
    支持的流式数据类型：
    - start: 开始处理
    - user_message: 用户消息
    - react_start: ReAct开始
    - iteration_start: 迭代开始
    - thinking_chunk: 思考片段（实时）
    - thought_complete: 思考完成
    - action: 执行的行动
    - action_executing: 行动执行中
    - observation: 行动结果
    - content: 最终答案内容（分块）
    - complete: 处理完成
    - error: 错误信息
    """
    try:
        # 添加详细的调试日志 - 使用print确保输出
        print(f"[ReactStream] ===== 开始ReAct流式聊天 =====")
        print(f"[ReactStream] 请求参数详情:")
        print(f"[ReactStream] - message: {request.message[:100]}...")
        print(f"[ReactStream] - conversation_id: {request.conversation_id}")
        print(f"[ReactStream] - user_id: {request.user_id}")
        print(f"[ReactStream] - include_history: {request.include_history}")
        print(f"[ReactStream] - max_history: {request.max_history}")

        logger.info(f"[ReactStream] ===== 开始ReAct流式聊天 =====")
        logger.info(f"[ReactStream] 请求参数详情:")
        logger.info(f"[ReactStream] - message: {request.message[:100]}...")
        logger.info(f"[ReactStream] - conversation_id: {request.conversation_id}")
        logger.info(f"[ReactStream] - user_id: {request.user_id}")
        logger.info(f"[ReactStream] - include_history: {request.include_history}")
        logger.info(f"[ReactStream] - max_history: {request.max_history}")

        # 检查数据库连接状态
        logger.info(f"[ReactStream] 数据库连接状态: {db is not None}")
        if db is not None:
            try:
                # 测试数据库连接
                db.execute(text("SELECT 1"))
                logger.info(f"[ReactStream] 数据库连接测试成功")
            except Exception as db_test_error:
                logger.error(f"[ReactStream] 数据库连接测试失败: {db_test_error}")

        # 检查用户认证状态
        logger.info(f"[ReactStream] 用户认证状态: {current_user is not None}")
        if current_user:
            logger.info(f"[ReactStream] 认证用户ID: {current_user.user_id}")
            logger.info(f"[ReactStream] 认证用户邮箱: {current_user.email}")

        # 获取对话历史
        chat_history = []
        if request.conversation_id and request.include_history:
            try:
                logger.info(f"[ReactStream] 尝试加载对话历史: {request.conversation_id}")
                conversation_service = HybridConversationService(db)
                messages = conversation_service.get_conversation_messages_hybrid(
                    conversation_id=request.conversation_id,
                    limit=request.max_history,
                    include_content=True
                )

                chat_history = [
                    {
                        "role": msg["role"],
                        "content": msg["content"]
                    }
                    for msg in messages
                ]

                logger.info(f"[ReactStream] 成功加载了 {len(chat_history)} 条历史消息")

            except Exception as e:
                logger.warning(f"[ReactStream] 加载对话历史失败: {e}")
        else:
            logger.info(f"[ReactStream] 跳过加载对话历史 - conversation_id: {request.conversation_id}, include_history: {request.include_history}")

        # 创建流式服务（传递数据库连接）
        streaming_service = ReactStreamingService(db=db)
        logger.info(f"[ReactStream] 创建ReactStreamingService成功")
        logger.info(f"[ReactStream] - 传入的db参数: {db is not None}")
        logger.info(f"[ReactStream] - 服务内部db状态: {streaming_service.db is not None}")

        # 获取用户ID（优先使用认证用户，其次使用请求中的用户ID）
        user_id = str(current_user.user_id) if current_user else (request.user_id or "anonymous")
        logger.info(f"[ReactStream] 用户ID确定逻辑:")
        logger.info(f"[ReactStream] - current_user存在: {current_user is not None}")
        logger.info(f"[ReactStream] - current_user.user_id: {current_user.user_id if current_user else 'None'}")
        logger.info(f"[ReactStream] - request.user_id: {request.user_id}")
        logger.info(f"[ReactStream] - 最终用户ID: {user_id}")
        logger.info(f"[ReactStream] - 对话ID: {request.conversation_id}")

        # 即将调用stream_react_process的参数检查
        logger.info(f"[ReactStream] 即将调用stream_react_process，参数检查:")
        logger.info(f"[ReactStream] - user_input: {request.message[:50]}...")
        logger.info(f"[ReactStream] - chat_history长度: {len(chat_history)}")
        logger.info(f"[ReactStream] - conversation_id: {request.conversation_id}")
        logger.info(f"[ReactStream] - user_id: {user_id}")
        logger.info(f"[ReactStream] - streaming_service.db: {streaming_service.db is not None}")

        # 返回流式响应
        return StreamingResponse(
            streaming_service.stream_react_process(
                user_input=request.message,
                chat_history=chat_history,
                conversation_id=request.conversation_id,
                user_id=user_id
            ),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Content-Type": "text/event-stream",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "*",
                "X-Accel-Buffering": "no"  # 禁用nginx缓冲
            }
        )
        
    except Exception as e:
        logger.error(f"[ReactStream] ReAct流式聊天失败: {e}")
        raise HTTPException(status_code=500, detail=f"ReAct流式聊天失败: {str(e)}")


@router.post("/react-stream-test")
async def react_stream_test(
    request: ReactStreamRequest
):
    """
    ReAct 流式测试接口 - 不需要数据库连接
    用于测试流式输出功能
    """
    try:
        logger.info(f"[ReactStreamTest] 匿名用户发起测试")
        
        # 创建流式服务
        streaming_service = ReactStreamingService()
        
        # 模拟简单的对话历史
        test_history = [
            {"role": "human", "content": "你好"},
            {"role": "assistant", "content": "您好！我是您的心理健康助手，很高兴为您服务。"}
        ] if request.include_history else []
        
        # 返回流式响应
        return StreamingResponse(
            streaming_service.stream_react_process(
                user_input=request.message,
                chat_history=test_history,
                conversation_id=request.conversation_id or "test_conversation"
            ),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Content-Type": "text/event-stream",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "*",
                "X-Accel-Buffering": "no"
            }
        )
        
    except Exception as e:
        logger.error(f"[ReactStreamTest] 测试失败: {e}")
        raise HTTPException(status_code=500, detail=f"测试失败: {str(e)}")


@router.get("/react-stream-demo")
async def react_stream_demo():
    """
    ReAct 流式演示接口 - 展示流式数据格式
    """
    async def demo_stream():
        """演示流式数据"""
        demo_data = [
            {"type": "start", "message": "🧠 AI开始思考...", "timestamp": time.time()},
            {"type": "user_message", "content": "我感到很焦虑", "timestamp": time.time()},
            {"type": "react_start", "message": "🔄 启动ReAct推理架构...", "timestamp": time.time()},
            {"type": "iteration_start", "iteration": 1, "message": "💭 开始第 1 次推理循环", "timestamp": time.time()},
            {"type": "thinking_chunk", "content": "用户表达了焦虑情绪", "iteration": 1, "timestamp": time.time()},
            {"type": "thinking_chunk", "content": "，我需要先分析情绪状态", "iteration": 1, "timestamp": time.time()},
            {"type": "thought_complete", "iteration": 1, "thought": "用户表达了焦虑情绪，我需要先分析情绪状态", "timestamp": time.time()},
            {"type": "action", "iteration": 1, "action": "emotion_analysis", "input": "我感到很焦虑", "timestamp": time.time()},
            {"type": "action_executing", "action": "emotion_analysis", "message": "🔧 执行工具: emotion_analysis", "timestamp": time.time()},
            {"type": "observation", "iteration": 1, "action": "emotion_analysis", "result": {"result": "检测到主要情绪: anxious (置信度: 0.85)"}, "timestamp": time.time()},
            {"type": "final_answer_start", "message": "✨ 生成最终回答...", "timestamp": time.time()},
            {"type": "content", "content": "我理解您正在经历焦虑", "timestamp": time.time()},
            {"type": "content", "content": "，这是很常见的情况。", "timestamp": time.time()},
            {"type": "content", "content": "让我为您提供一些帮助...", "timestamp": time.time()},
            {"type": "complete", "message": "✅ ReAct处理完成", "timestamp": time.time()}
        ]
        
        for data in demo_data:
            yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
            await asyncio.sleep(0.5)  # 模拟处理时间
    
    return StreamingResponse(
        demo_stream(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "text/event-stream"
        }
    )


@router.get("/react-stream-status")
async def react_stream_status():
    """
    ReAct 流式服务状态检查
    """
    try:
        # 检查服务状态
        streaming_service = ReactStreamingService()
        
        return {
            "status": "healthy",
            "service": "ReactStreamingService",
            "tools_available": list(streaming_service.tools.keys()),
            "max_iterations": streaming_service.max_iterations,
            "llm_model": streaming_service.llm.model_name,
            "timestamp": time.time()
        }
        
    except Exception as e:
        logger.error(f"[ReactStreamStatus] 状态检查失败: {e}")
        return {
            "status": "error",
            "error": str(e),
            "timestamp": time.time()
        }


# 流式数据格式说明
STREAM_DATA_FORMAT_DOC = """
# ReAct 流式数据格式说明

## 数据类型

### 1. 开始和状态
- `start`: 处理开始
- `react_start`: ReAct架构启动
- `iteration_start`: 推理循环开始

### 2. 思考过程
- `thinking_chunk`: 实时思考片段（来自DeepSeek reasoning_content）
- `thought_complete`: 完整思考内容

### 3. 行动执行
- `action`: 要执行的行动
- `action_executing`: 行动执行中
- `observation`: 行动执行结果

### 4. 内容输出
- `content`: 最终答案内容（分块输出）
- `final_answer_start`: 开始输出最终答案

### 5. 特殊情况
- `safety_triggered`: 安全检查触发
- `error`: 错误信息
- `complete`: 处理完成

## 数据结构示例

```json
{
  "type": "thinking_chunk",
  "content": "用户表达了焦虑情绪",
  "iteration": 1,
  "timestamp": 1234567890.123
}
```

```json
{
  "type": "action",
  "iteration": 1,
  "action": "emotion_analysis",
  "input": "我感到很焦虑",
  "timestamp": 1234567890.123
}
```

```json
{
  "type": "content",
  "content": "我理解您的感受",
  "timestamp": 1234567890.123
}
```
"""

@router.get("/react-stream-docs")
async def react_stream_docs():
    """
    ReAct 流式API文档
    """
    return {
        "title": "ReAct 流式聊天API",
        "description": "支持思考过程实时流式输出的ReAct聊天接口",
        "endpoints": {
            "/react-stream": "主要的流式聊天接口",
            "/react-stream-test": "测试接口（无需数据库）",
            "/react-stream-demo": "演示接口（展示数据格式）",
            "/react-stream-status": "服务状态检查",
            "/react-stream-docs": "API文档"
        },
        "data_format": STREAM_DATA_FORMAT_DOC,
        "usage_example": {
            "request": {
                "message": "我感到很焦虑",
                "conversation_id": "optional_conversation_id",
                "include_history": True,
                "max_history": 10
            },
            "response": "text/event-stream with JSON data"
        }
    }
